<template>
  <div class="generate-history">
    <!-- 筛选条件 -->
    <div class="filter-container">
      <el-form :model="filterForm" inline size="mini">
        <el-form-item label="生成时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="文件格式">
          <el-select v-model="filterForm.format" clearable>
            <el-option label="Word" value="word"></el-option>
            <el-option label="PDF" value="pdf"></el-option>
            <el-option label="HTML" value="html"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="生成状态">
          <el-select v-model="filterForm.status" clearable>
            <el-option label="成功" value="success"></el-option>
            <el-option label="失败" value="error"></el-option>
            <el-option label="生成中" value="generating"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 历史记录表格 -->
    <div class="history-table">
      <el-table
        :data="historyList"
        v-loading="loading"
        empty-text="暂无生成历史"
        style="width: 100%"
        size="mini"
      >
        <el-table-column prop="filename" label="文件名称" min-width="200">
          <template #default="scope">
            <div class="filename-cell">
              <i :class="getFileIcon(scope.row.format)" class="file-icon"></i>
              <span class="filename">{{ scope.row.filename }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="templateName" label="使用模板" width="150">
          <template #default="scope">
            <el-tooltip :content="scope.row.templateName" placement="top">
              <span class="template-name">{{ scope.row.templateName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column prop="sampleNo" label="样品编号" width="120">
          <template #default="scope">
            <span class="sample-no">{{ scope.row.sampleNo }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="format" label="文件格式" width="80">
          <template #default="scope">
            <el-tag size="small" :type="getFormatTag(scope.row.format)">
              {{ scope.row.format.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="fileSize" label="文件大小" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusTag(scope.row.status)" 
              size="small"
              :effect="scope.row.status === 'success' ? 'dark' : 'plain'"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="generateTime" label="生成时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.generateTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="generateUser" label="生成人" width="100">
          <template #default="scope">
            {{ scope.row.generateUser || '系统' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              type="text"
              size="mini"
              @click="downloadFile(scope.row)"
              :disabled="scope.row.status !== 'success'"
              icon="el-icon-download"
            >
              下载
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="viewDetails(scope.row)"
              icon="el-icon-view"
            >
              详情
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="deleteHistory(scope.row)"
              style="color: #f56c6c"
              icon="el-icon-delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        size="mini"
      >
      </el-pagination>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      title="生成记录详情"
      :visible.sync="detailDialog.visible"
      width="600px"
    >
      <el-descriptions :column="2" border size="medium" v-if="detailDialog.data">
        <el-descriptions-item label="文件名称">
          {{ detailDialog.data.filename }}
        </el-descriptions-item>
        <el-descriptions-item label="文件格式">
          <el-tag :type="getFormatTag(detailDialog.data.format)">
            {{ detailDialog.data.format.toUpperCase() }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="样品编号">
          {{ detailDialog.data.sampleNo }}
        </el-descriptions-item>
        <el-des-items label="模板名称">
          {{ detailDialog.data.templateName }}
        </el-descriptions-item>
        <el-descriptions-item label="文件大小">
          {{ formatFileSize(detailDialog.data.fileSize) }}
        </el-descriptions-item>
        <el-descriptions-item label="生成状态">
          <el-tag :type="getStatusTag(detailDialog.data.status)">
            {{ getStatusText(detailDialog.data.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="生成时间">
          {{ formatDateTime(detailDialog.data.generateTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="生成人">
          {{ detailDialog.data.generateUser }}
        </el-descriptions-item>
        <el-descriptions-item label="耗时" :span="2">
          {{ detailDialog.data.duration || 0 }} 秒
        </el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2" v-if="detailDialog.data.error">
          <div class="error-message">
            {{ detailDialog.data.error }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialog.visible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="downloadFile(detailDialog.data)"
          :disabled="!detailDialog.data || detailDialog.data.status !== 'success'"
        >
          下载文件
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { formatDate } from '@/utils/tools'

export default {
  name: 'GenerateHistory',
  props: {
    sampleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 筛选表单
      filterForm: {
        dateRange: [],
        format: '',
        status: ''
      },
      
      // 历史记录数据
      historyList: [],
      loading: false,
      
      // 分页配置
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      
      // 详情对话框
      detailDialog: {
        visible: false,
        data: null
      }
    }
  },
  created() {
    this.loadHistory()
  },
  methods: {
    /**
     * 加载生成历史
     */
    async loadHistory() {
      this.loading = true
      try {
        // 模拟API调用
        const mockHistory = this.getMockHistory()
        this.historyList = mockHistory
        this.pagination.total = mockHistory.length
      } catch (error) {
        console.error('加载生成历史失败:', error)
        this.$message.error('加载生成历史失败')
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 获取模拟历史数据
     */
    getMockHistory() {
      return [
        {
          id: 'history_001',
          filename: '钢筋拉伸试验报告_20240120.docx',
          templateName: '标准检测报告',
          sampleNo: 'SAMPLE-2024-001',
          format: 'word',
          fileSize: 24576,
          status: 'success',
          generateTime: '2024-01-20T15:30:00',
          generateUser: '管理员',
          duration: 3.2
        },
        {
          id: 'history_002',
          filename: '混凝土抗压强度记录_20240119.pdf',
          templateName: '原始记录模板',
          sampleNo: 'SAMPLE-2024-002',
          format: 'pdf',
          fileSize: 153600,
          status: 'success',
          generateTime: '2024-01-19T14:20:00',
          generateUser: '测试员',
          duration: 2.8
        },
        {
          id: 'history_003',
          filename: '综合检测报告_20240118.docx',
          templateName: '详细检测报告',
          sampleNo: 'SAMPLE-2024-003',
          format: 'word',
          fileSize: 0,
          status: 'error',
          generateTime: '2024-01-18T16:45:00',
          generateUser: '管理员',
          duration: 0,
          error: '模板文件不存在'
        }
      ]
    },
    
    /**
     * 获取文件图标
     */
    getFileIcon(format) {
      const iconMap = {
        word: 'el-icon-document',
        pdf: 'el-icon-document',
        html: 'el-icon-document'
      }
      return iconMap[format] || 'el-icon-document'
    },
    
    /**
     * 获取格式标签样式
     */
    getFormatTag(format) {
      const tagMap = {
        word: 'primary',
        pdf: 'danger',
        html: 'success'
      }
      return tagMap[format] || 'info'
    },
    
    /**
     * 获取状态标签样式
     */
    getStatusTag(status) {
      const tagMap = {
        success: 'success',
        error: 'danger',
        generating: 'warning'
      }
      return tagMap[status] || 'info'
    },
    
    /**
     * 获取状态文本
     */
    getStatusText(status) {
      const textMap = {
        success: '成功',
        error: '失败',
        generating: '生成中'
      }
      return textMap[status] || '未知'
    },
    
    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B'
      
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    /**
     * 格式化日期时间
     */
    formatDateTime(dateTime) {
      return formatDate(dateTime, 'YYYY-MM-DD HH:mm:ss')
    },
    
    /**
     * 处理筛选
     */
    handleFilter() {
      this.pagination.current = 1
      this.loadHistory()
    },
    
    /**
     * 重置筛选
     */
    resetFilter() {
      this.filterForm = {
        dateRange: [],
        format: '',
        status: ''
      }
      this.pagination.current = 1
      this.loadHistory()
    },
    
    /**
     * 下载文件
     */
    downloadFile(record) {
      if (record.status !== 'success') {
        this.$message.warning('文件生成失败，无法下载')
        return
      }
      
      // 模拟下载
      this.$message.success(`开始下载: ${record.filename}`)
      
      // 实际项目中应该调用下载API
      // this.$api.report.download(record.id)
    },
    
    /**
     * 查看详情
     */
    viewDetails(record) {
      this.detailDialog = {
        visible: true,
        data: record
      }
    },
    
    /**
     * 删除历史记录
     */
    async deleteHistory(record) {
      try {
        await this.$confirm(
          `确定要删除生成记录"${record.filename}"吗？`,
          '删除确认',
          {
            type: 'warning',
            confirmButtonText: '确定删除',
            cancelButtonText: '取消'
          }
        )
        
        // 调用API删除记录
        // await this.$api.history.delete(record.id)
        
        this.$message.success('删除成功')
        this.loadHistory()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除历史记录失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    
    /**
     * 分页大小改变
     */
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadHistory()
    },
    
    /**
     * 当前页改变
     */
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadHistory()
    }
  }
}
</script>

<style scoped>
.generate-history {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.history-table {
  flex: 1;
  overflow: hidden;
}

.filename-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #409eff;
  font-size: 16px;
}

.filename {
  font-weight: 500;
}

.template-name {
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sample-no {
  font-weight: 600;
  color: #409eff;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.error-message {
  color: #f56c6c;
  background: #fef0f0;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-container .el-form--inline .el-form-item {
    margin-bottom: 10px;
  }
  
  .filename-cell {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>